<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2019 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2019-06-22
 * Time: 21:27
 */

namespace App\Repositories\Eloquent;


use App\Models\Item;
use App\Repositories\Contracts\ItemRepositoryInterface;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

class ItemRepository extends BaseRepository implements ItemRepositoryInterface
{
    /**
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|string
     */
    public function model()
    {
        // TODO: Implement getModel() method.
        return Item::class;
    }

    /**
     * @param array $attributes
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public function create(array $attributes)
    {
        if (!isset($attributes['shop_id'])){
            if ($shop = Auth::user()->shop){
                $attributes['shop_id'] = $shop->shop_id;
            }
        }
        return parent::create($attributes); // TODO: Change the autogenerated stub
    }

    /**
     * @param Item $item
     * @param $content
     * @return Item
     */
    public function updateContent($item, $content)
    {
        // TODO: Implement updateContent() method.
        if (is_string($content)) {
            $item->content->update(['content' => $content]);
        } else {
            $item->content->update($content);
        }
        return $item;
    }

    /**
     * @param Item $item
     * @param array $images
     * @return Item
     */
    public function updateImages($item, array $images)
    {
        // TODO: Implement updateImages() method.
        if ($images) {
            $firstImg = Arr::first($images);
            $item->thumb = $firstImg['thumb'];
            $item->image = $firstImg['image'];
            $item->save();

            $displayorder = 0;
            $imageIds = $item->images->pluck('id');
            foreach ($images as $image) {
                $imgid = $image['id'];
                $image['displayorder'] = $displayorder++;
                if ($imageIds->has($imgid)) {
                    $item->images()->whereKey($imgid)->update($image);
                    $imageIds->forget($imgid);
                } else {
                    $item->images()->create($image);
                }
            }
            $item->images()->whereKey($imageIds)->delete();
        } else {
            $item->images()->delete();
        }
        return $item;
    }
}
